Tic Tac Toe Winner in Javascript and html [closed]

Posted by Yehuda G on Programmers See other posts from Programmers or by Yehuda G
Published on 2012-09-25T19:41:48Z Indexed on 2012/09/25 21:49 UTC
Read the original article Hit count: 404

Filed under:
|

I am writing a tic tac toe game using html, css, and JavaScript. I have my JavaScript in an external .js file being referenced into the .html file. Within the .js file, I have a function called playerMove, which allows the player to make his/her move and switches between player 'x' and 'o'. What I am trying to do is determine the winner.

Here is what I have: each square, when onclick(this), references playerMove(piece). After each move is made, I want to run an if statement to check for the winner, but am unsure if the parameters would include a reference to 'piece' or a,b, and c. Any suggestions would be greatly appreciated.

Javascript:

var turn = 0;   
a = document.getElementById("topLeftSquare").innerHTML;
b = document.getElementById("topMiddleSquare").innerHTML;
c = document.getElementById("topRightSquare").innerHTML;

function playerMove(piece) {
var win;
if(piece.innerHTML != 'X' && piece.innerHTML != 'O'){
    if(turn % 2 == 0){
        document.getElementById('playerDisplay').innerHTML= "X Plays " + printEquation(1);
        piece.innerHTML = 'X';
        window.setInterval("X", 10000)
        piece.style.color = "red";
        if(piece.innerHTML == 'X')
            window.alert("X WINS!");
    }
    else {
        document.getElementById('playerDisplay').innerHTML= "O Plays " + printEquation(1);
        piece.innerHTML = 'O';
        piece.style.color = "brown";

    }

    turn+=1;
}

html:

<div id="board">
            <div class="topLeftSquare" onclick="playerMove(this)">

            </div>
            <div class="topMiddleSquare" onclick="playerMove(this)">

            </div>
            <div class="topRightSquare" onclick="playerMove(this)">

            </div>
            <div class="middleLeftSquare" onclick="playerMove(this)">

            </div>
            <div class="middleSquare" onclick="playerMove(this)">

            </div>
            <div class="middleRightSquare" onclick="playerMove(this)">

            </div>
            <div class="bottomLeftSquare" onclick="playerMove(this)">

            </div>
            <div class="bottomMiddleSquare" onclick="playerMove(this)">

            </div>
            <div class="bottomRightSquare" onclick="playerMove(this)">

            </div>

        </div>

© Programmers or respective owner

Related posts about JavaScript

Related posts about html